const Articles = require('../db/index').Articles

const jwt = require('jsonwebtoken')
// const checkToken = require('../utils/checkToken.js') // 验证token

//获取文章列表
const getArticleList = async (ctx) => {
  const { page,size,title,author,createDate,modifyDate } = ctx.request.query

  try {
    const articles = await Articles.find().limit(Number(size)).skip((Number(page) - 1) * Number(size));
    const total = await Articles.find().count()
    ctx.body = {
      data:articles,
      total:total
    }
  } catch (err) {
      ctx.body = {
          code: -1,
          msg: err
      }
  }
}

const addArticle = async (ctx) => {
  const token = ctx.get('X-Token')
  const now = new Date()
  const data = {
    ...ctx.request.body,
    createDate:now,
    modifyDate:now
  }
  try {
    const doc = await Articles.insertMany(data)
    ctx.body = {
      data:doc
    }
  } catch (err) {
      ctx.body = {
          code: -1,
          msg: err
      }
  }
}

const articleFunc = {
  getArticleList,
  addArticle
};
module.exports = articleFunc